package com.hmall.user.web;

import cn.hutool.core.util.StrUtil;
import com.hmall.user.dto.LoginDto;
import com.hmall.user.pojo.Newuser;
import com.hmall.user.pojo.User;
import com.hmall.user.service.impl.UserService;
import com.hmall.user.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 登录
     */
    @Resource
    private UserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @PostMapping("/login")
    public LoginVo findAddressById(@RequestBody LoginDto dto, @RequestHeader (required = false) String authorization) {
      int  result = userService.Checkpwd(dto.getUsername(), dto.getPassword());
        log.info("登录：{}", dto);
        log.info("登录结果：{}", result);
        log.info("请求头",authorization);
        if(result==0){
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "用户名或密码错误");
        }
        return LoginVo.builder().username(dto.getUsername())
                .token(String.valueOf(System.currentTimeMillis()))
                .build();

    }
    @GetMapping("check/{name}/{password}")
    public int check(@PathVariable("name") String name,@PathVariable("password") String password){
        return userService.check(name,password);
    }
    @PostMapping("code")
    public int code(@RequestBody Newuser user) throws Exception {

        int code=userService.code(user.getPhone());
        String codee=code+"";
        stringRedisTemplate.opsForValue().set(user.getPhone(),codee,5, TimeUnit.MINUTES);
        return code;
    }
    @PostMapping("register")
    public int register(@RequestBody Newuser user){
        User user1 = new User();
        user1.setUsername(user.getUsername());
        user1.setPassword(user.getPassword());
        user1.setPhone(user.getPhone());
        String code1=user.getCode();
        String code2=stringRedisTemplate.opsForValue().get(user.getPhone());
        if(!StrUtil.equals(code1,code2)){
            log.info(code2);
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "验证码错误");
        }
       if(userService.register(user1)) {
          return 1;
       }
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "用户名已存在");
    }
    //根据用户名查id
    @GetMapping("find/{username}")
    public int find(@PathVariable String username){
        return userService.find(username);
    }
}
